<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  getTravelNoteList,
  adminUpdateTravelNote,
  deleteTravelNote
} from '@/api/travelNote'
import {
  getTravelPlanList,
  updateTravelPlan,
  deleteTravelPlan
} from '@/api/travelPlan'
import { getCityList, updateCity } from '@/api/city'
import {
  Location,
  Star,
  Top,
  View,
  Delete,
  Calendar,
  Picture,
  Upload
} from '@element-plus/icons-vue'
import { uploadFile } from '@/api/upload'

const router = useRouter()

// Tab 切换
const activeTab = ref('cities')

// 统计数据
const statistics = ref({
  cities: 0,
  hotNotes: 0,
  hotPlans: 0,
  community: 0
})

// ========== 城市管理 ==========
const cityList = ref([])
const cityLoading = ref(false)
const cityTotal = ref(0)
const cityParams = ref({
  page: 1,
  pageSize: 10
})

// 加载城市列表
const loadCityList = async () => {
  cityLoading.value = true
  try {
    const result = await getCityList(cityParams.value)
    if (result.success) {
      if (Array.isArray(result.data)) {
        cityList.value = result.data
        cityTotal.value = result.data.length
      } else {
        cityList.value = result.data.list || []
        cityTotal.value = result.data.total || 0
      }
    }
  } catch (error) {
    console.error('加载城市列表失败:', error)
  } finally {
    cityLoading.value = false
  }
}

// 上传城市封面
const handleCityImageUpload = async (row) => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'

  input.onchange = async (e) => {
    const file = e.target.files[0]
    if (!file) return

    try {
      const result = await uploadFile(file)
      if (result.success && result.data.url) {
        const updateResult = await updateCity(row.id, {
          image: result.data.url
        })
        if (updateResult.success) {
          ElMessage.success('封面图更新成功')
          loadCityList()
        } else {
          ElMessage.error('更新失败')
        }
      } else {
        ElMessage.error('上传失败')
      }
    } catch (error) {
      console.error('上传失败:', error)
      ElMessage.error('上传失败')
    }
  }

  input.click()
}

// ========== 热门游记 ==========
const noteList = ref([])
const noteLoading = ref(false)
const noteTotal = ref(0)
const noteParams = ref({
  page: 1,
  pageSize: 10
})

// 加载热门游记（按收藏数排序）
const loadNoteList = async () => {
  noteLoading.value = true
  try {
    const result = await getTravelNoteList({
      status: 'approved',
      visibility: 'public',
      order_by: 'favorite_count',
      order: 'DESC',
      ...noteParams.value
    })
    if (result.success) {
      noteList.value = result.data.list || []
      noteTotal.value = result.data.total || 0
    }
  } catch (error) {
    console.error('加载热门游记失败:', error)
  } finally {
    noteLoading.value = false
  }
}

// 切换游记置顶
const toggleNoteTop = async (row) => {
  try {
    const result = await adminUpdateTravelNote(row.id, {
      is_top: !row.is_top
    })
    if (result.success) {
      ElMessage.success(`${row.is_top ? '取消置顶' : '设置置顶'}成功`)
      loadNoteList()
      loadStatistics()
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// ========== 热门行程 ==========
const planList = ref([])
const planLoading = ref(false)
const planTotal = ref(0)
const planParams = ref({
  page: 1,
  pageSize: 10
})

// 加载热门旅行计划
const loadPlanList = async () => {
  planLoading.value = true
  try {
    const result = await getTravelPlanList({
      status: 'approved',
      is_public: true,
      ...planParams.value
    })
    if (result.success) {
      if (Array.isArray(result.data)) {
        const filteredPlans = result.data.filter(
          (plan) => plan.status === 'approved' && plan.isPublic
        )
        planList.value = filteredPlans
        planTotal.value = filteredPlans.length
      } else {
        planList.value = result.data.list || []
        planTotal.value = result.data.total || 0
      }
    }
  } catch (error) {
    console.error('加载热门旅行计划失败:', error)
  } finally {
    planLoading.value = false
  }
}

// 切换计划置顶
const togglePlanTop = async (row) => {
  try {
    const result = await updateTravelPlan(row.id, {
      is_top: !row.is_top
    })
    if (result.success) {
      ElMessage.success(`${row.is_top ? '取消置顶' : '设置置顶'}成功`)
      loadPlanList()
      loadStatistics()
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// ========== 社区精选 ==========
const communityList = ref([])
const communityLoading = ref(false)
const communityTotal = ref(0)
const communityParams = ref({
  page: 1,
  pageSize: 10
})

// 加载社区精选（按浏览量排序）
const loadCommunityList = async () => {
  communityLoading.value = true
  try {
    const result = await getTravelNoteList({
      status: 'approved',
      visibility: 'public',
      order_by: 'view_count',
      order: 'DESC',
      ...communityParams.value
    })
    if (result.success) {
      communityList.value = result.data.list || []
      communityTotal.value = result.data.total || 0
    }
  } catch (error) {
    console.error('加载社区精选失败:', error)
  } finally {
    communityLoading.value = false
  }
}

// 切换社区置顶
const toggleCommunityTop = async (row) => {
  try {
    const result = await adminUpdateTravelNote(row.id, {
      is_top: !row.is_top
    })
    if (result.success) {
      ElMessage.success(`${row.is_top ? '取消置顶' : '设置置顶'}成功`)
      loadCommunityList()
      loadStatistics()
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// ========== 通用功能 ==========
// 加载统计数据
const loadStatistics = async () => {
  try {
    const [cityRes, noteRes, planRes, communityRes] = await Promise.all([
      getCityList({ page: 1, pageSize: 1 }),
      getTravelNoteList({
        status: 'approved',
        visibility: 'public',
        page: 1,
        pageSize: 1
      }),
      getTravelPlanList({
        status: 'approved',
        is_public: true,
        page: 1,
        pageSize: 1
      }),
      getTravelNoteList({
        status: 'approved',
        visibility: 'public',
        page: 1,
        pageSize: 1
      })
    ])

    if (cityRes.success) {
      statistics.value.cities = Array.isArray(cityRes.data)
        ? cityRes.data.length
        : cityRes.data.total || 0
    }
    if (noteRes.success) {
      statistics.value.hotNotes = noteRes.data.total || 0
    }
    if (planRes.success) {
      statistics.value.hotPlans = Array.isArray(planRes.data)
        ? planRes.data.filter((p) => p.status === 'approved' && p.isPublic)
            .length
        : planRes.data.total || 0
    }
    if (communityRes.success) {
      statistics.value.community = communityRes.data.total || 0
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// Tab 切换
const handleTabChange = (tab) => {
  if (tab === 'cities') {
    loadCityList()
  } else if (tab === 'notes') {
    loadNoteList()
  } else if (tab === 'plans') {
    loadPlanList()
  } else if (tab === 'community') {
    loadCommunityList()
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 截取文本
const truncateText = (text, length = 30) => {
  if (!text) return '-'
  return text.length > length ? text.substring(0, length) + '...' : text
}

onMounted(() => {
  loadStatistics()
  loadCityList()
})
</script>

<template>
  <div class="recommend-manage">
    <h2 class="page-title">⚙️ 推荐设置</h2>
    <p class="page-desc">
      配置首页展示内容，包括热门城市、热门游记、热门行程和社区精选
    </p>

    <!-- 统计卡片 -->
    <div class="statistics-grid">
      <el-card class="stat-card cities" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon :size="32"><Location /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.cities }}</div>
            <div class="stat-label">热门城市</div>
            <div class="stat-tip">按推荐数排序</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card notes" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon :size="32"><Star /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.hotNotes }}</div>
            <div class="stat-label">热门游记</div>
            <div class="stat-tip">按收藏数排序，最多6个</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card plans" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon :size="32"><Calendar /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.hotPlans }}</div>
            <div class="stat-label">热门行程</div>
            <div class="stat-tip">最新公开计划</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card community" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon :size="32"><View /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.community }}</div>
            <div class="stat-label">社区精选</div>
            <div class="stat-tip">按浏览量排序，最多4个</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- Tab 内容 -->
    <el-card class="content-card">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 城市管理 -->
        <el-tab-pane label="🏙️ 热门城市" name="cities">
          <div class="tab-desc">
            管理城市信息和封面图，首页展示按推荐数排序的TOP6城市
          </div>
          <el-table :data="cityList" v-loading="cityLoading" border stripe>
            <el-table-column label="封面" width="100">
              <template #default="{ row }">
                <el-image
                  v-if="row.image"
                  :src="row.image"
                  fit="cover"
                  style="width: 60px; height: 60px; border-radius: 4px"
                  :preview-src-list="[row.image]"
                  :z-index="9999"
                  preview-teleported
                />
                <span v-else style="color: #999; font-size: 12px">无</span>
              </template>
            </el-table-column>

            <el-table-column prop="name" label="城市名称" width="120" />

            <el-table-column prop="description" label="描述" min-width="200">
              <template #default="{ row }">
                {{ truncateText(row.description, 40) }}
              </template>
            </el-table-column>

            <el-table-column label="推荐数" width="100" sortable>
              <template #default="{ row }">
                <el-tag type="warning">{{ row.recommendations || 0 }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="浏览量" width="100">
              <template #default="{ row }">
                {{ row.views || 0 }}
              </template>
            </el-table-column>

            <el-table-column label="评分" width="100">
              <template #default="{ row }">
                <el-rate
                  :model-value="row.rating || 0"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value}"
                />
              </template>
            </el-table-column>

            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  size="small"
                  :icon="Upload"
                  @click="handleCityImageUpload(row)"
                >
                  更换封面
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-if="cityTotal > 0"
            class="pagination"
            :current-page="cityParams.page"
            :page-size="cityParams.pageSize"
            layout="total, prev, pager, next"
            :total="cityTotal"
            @current-change="
              (page) => {
                cityParams.page = page
                loadCityList()
              }
            "
            background
          />
        </el-tab-pane>

        <!-- 热门游记 -->
        <el-tab-pane label="⭐ 热门游记" name="notes">
          <div class="tab-desc">按收藏数排序，首页展示TOP6（置顶权重最高）</div>
          <el-table :data="noteList" v-loading="noteLoading" border stripe>
            <el-table-column type="index" label="排名" width="70" />

            <el-table-column label="封面" width="80">
              <template #default="{ row }">
                <el-image
                  v-if="row.cover_image"
                  :src="row.cover_image"
                  fit="cover"
                  style="width: 50px; height: 50px; border-radius: 4px"
                  :preview-src-list="[row.cover_image]"
                  :z-index="9999"
                  preview-teleported
                />
                <span v-else style="color: #999; font-size: 12px">无</span>
              </template>
            </el-table-column>

            <el-table-column prop="title" label="标题" min-width="200" />

            <el-table-column prop="city" label="城市" width="100" />

            <el-table-column label="收藏数" width="100" sortable>
              <template #default="{ row }">
                <span style="color: #f56c6c; font-weight: 600">
                  {{ row.favorite_count || 0 }}
                </span>
              </template>
            </el-table-column>

            <el-table-column label="浏览量" width="100">
              <template #default="{ row }">
                {{ row.view_count || 0 }}
              </template>
            </el-table-column>

            <el-table-column label="点赞" width="100">
              <template #default="{ row }">
                {{ row.like_count || 0 }}
              </template>
            </el-table-column>

            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag v-if="row.is_top" type="danger" size="small"
                  >置顶</el-tag
                >
                <el-tag v-else type="success" size="small">正常</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button
                  :type="row.is_top ? 'warning' : 'primary'"
                  size="small"
                  :icon="Top"
                  @click="toggleNoteTop(row)"
                >
                  {{ row.is_top ? '取消置顶' : '置顶' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-if="noteTotal > 0"
            class="pagination"
            :current-page="noteParams.page"
            :page-size="noteParams.pageSize"
            layout="total, prev, pager, next"
            :total="noteTotal"
            @current-change="
              (page) => {
                noteParams.page = page
                loadNoteList()
              }
            "
            background
          />
        </el-tab-pane>

        <!-- 热门行程 -->
        <el-tab-pane label="📅 热门行程" name="plans">
          <div class="tab-desc">
            最新公开的旅行计划，首页展示TOP6（置顶权重最高）
          </div>
          <el-table :data="planList" v-loading="planLoading" border stripe>
            <el-table-column type="index" label="排名" width="70" />

            <el-table-column label="封面" width="80">
              <template #default="{ row }">
                <el-image
                  v-if="row.coverImage"
                  :src="row.coverImage"
                  fit="cover"
                  style="width: 50px; height: 50px; border-radius: 4px"
                  :preview-src-list="[row.coverImage]"
                  :z-index="9999"
                  preview-teleported
                />
                <span v-else style="color: #999; font-size: 12px">无</span>
              </template>
            </el-table-column>

            <el-table-column prop="title" label="标题" min-width="200" />

            <el-table-column label="天数" width="80">
              <template #default="{ row }">
                <el-tag type="info" size="small">{{ row.days }}天</el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="cityName" label="城市" width="100" />

            <el-table-column label="出发日期" width="120">
              <template #default="{ row }">
                {{ row.startDate || '-' }}
              </template>
            </el-table-column>

            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag v-if="row.is_top" type="danger" size="small"
                  >置顶</el-tag
                >
                <el-tag v-else type="success" size="small">正常</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="创建时间" width="140">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button
                  :type="row.is_top ? 'warning' : 'primary'"
                  size="small"
                  :icon="Top"
                  @click="togglePlanTop(row)"
                >
                  {{ row.is_top ? '取消置顶' : '置顶' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-if="planTotal > 0"
            class="pagination"
            :current-page="planParams.page"
            :page-size="planParams.pageSize"
            layout="total, prev, pager, next"
            :total="planTotal"
            @current-change="
              (page) => {
                planParams.page = page
                loadPlanList()
              }
            "
            background
          />
        </el-tab-pane>

        <!-- 社区精选 -->
        <el-tab-pane label="🌐 社区精选" name="community">
          <div class="tab-desc">按浏览量排序，首页展示TOP4（置顶权重最高）</div>
          <el-table
            :data="communityList"
            v-loading="communityLoading"
            border
            stripe
          >
            <el-table-column type="index" label="排名" width="70" />

            <el-table-column label="封面" width="80">
              <template #default="{ row }">
                <el-image
                  v-if="row.cover_image"
                  :src="row.cover_image"
                  fit="cover"
                  style="width: 50px; height: 50px; border-radius: 4px"
                  :preview-src-list="[row.cover_image]"
                  :z-index="9999"
                  preview-teleported
                />
                <span v-else style="color: #999; font-size: 12px">无</span>
              </template>
            </el-table-column>

            <el-table-column prop="title" label="标题" min-width="200" />

            <el-table-column prop="city" label="城市" width="100" />

            <el-table-column label="浏览量" width="100" sortable>
              <template #default="{ row }">
                <span style="color: #e6a23c; font-weight: 600">
                  {{ row.view_count || 0 }}
                </span>
              </template>
            </el-table-column>

            <el-table-column label="点赞" width="100">
              <template #default="{ row }">
                {{ row.like_count || 0 }}
              </template>
            </el-table-column>

            <el-table-column label="评论" width="100">
              <template #default="{ row }">
                {{ row.comment_count || 0 }}
              </template>
            </el-table-column>

            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag v-if="row.is_top" type="danger" size="small"
                  >置顶</el-tag
                >
                <el-tag v-else type="success" size="small">正常</el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button
                  :type="row.is_top ? 'warning' : 'primary'"
                  size="small"
                  :icon="Top"
                  @click="toggleCommunityTop(row)"
                >
                  {{ row.is_top ? '取消置顶' : '置顶' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-if="communityTotal > 0"
            class="pagination"
            :current-page="communityParams.page"
            :page-size="communityParams.pageSize"
            layout="total, prev, pager, next"
            :total="communityTotal"
            @current-change="
              (page) => {
                communityParams.page = page
                loadCommunityList()
              }
            "
            background
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<style scoped>
.recommend-manage {
  padding: 20px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-desc {
  margin: 0 0 20px 0;
  font-size: 14px;
  color: #909399;
}

.tab-desc {
  padding: 0 0 16px 0;
  font-size: 14px;
  color: #606266;
  background: #f5f7fa;
  padding: 12px 16px;
  border-radius: 4px;
  margin-bottom: 16px;
}

/* 统计卡片 */
.statistics-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

@media (max-width: 1200px) {
  .statistics-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-card.cities .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-card.notes .stat-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.stat-card.plans .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.stat-card.community .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  margin-bottom: 6px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.stat-tip {
  font-size: 12px;
  color: #909399;
}

/* 内容卡片 */
.content-card {
  border-radius: 8px;
}

.content-card :deep(.el-tabs__content) {
  padding: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式 */
@media (max-width: 768px) {
  .recommend-manage {
    padding: 10px;
  }

  .statistics-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }

  .stat-value {
    font-size: 24px;
  }
}
</style>
